import { Provide } from '@midwayjs/core'
import { Repository } from 'typeorm'
import { InjectEntityModel } from '@midwayjs/typeorm'
import { MaterialDonate } from '../../entities/MaterialDonate.entity'
import { MaterialDonateWithMaterial } from '../../types/admin'

@Provide()
export class DonateService {
  @InjectEntityModel(MaterialDonate)
  repo!: Repository<MaterialDonate>

  async list(queryInfo: any) {
    const { page = 1, pageSize = 10 } = queryInfo
    // 创建查询构建器
    const queryBuilder = this.repo.createQueryBuilder('md')
      .leftJoin('md.material', 'm')
      // 直接设置字段别名
      .select([
        'md.id AS id',
        'md.createTime AS createTime',
        'md.count AS count',
        'md.price AS price',
        'md.title AS title',
        'm.name AS materialName'
      ])
      .orderBy('md.id', 'DESC');
    
    if(queryInfo?.price) {
      queryBuilder.andWhere("md.price = :price", { price: queryInfo?.price || 0 })
    }
    if(queryInfo?.title) {
      queryBuilder.andWhere("md.title LIKE :title", { title: `%${queryInfo?.title || ''}%` })
    }
    // 获取总数
    const total = await queryBuilder.getCount();
    
    // 获取分页数据
    const items = await queryBuilder
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .getRawMany();

    return {
      total,
      items: items as MaterialDonateWithMaterial[],
    }
  }

  async add(data: Partial<MaterialDonate>) {  
    const obj = this.repo.create(data)
    return this.repo.save(obj)
  }

  async edit(data: Partial<MaterialDonate>) {
    return this.repo.save(data)
  }

  async delete(id: number) {
    return this.repo.delete(id)
  }
}
